package cn.com.chengq.filesshared.config;

import com.sun.faces.config.ConfigureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.faces.webapp.FacesServlet;
import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

// @Configuration
public class FacesServletConfig extends SpringBootServletInitializer implements ServletContextAware
{

    private static Logger log = LoggerFactory.getLogger(FacesServletConfig.class);


    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName(
                        "redirect:/faces/index.xhtml");
            }
        };
    }

    @Bean
    public ServletRegistrationBean<FacesServlet> facesServletRegistration() {
        ServletRegistrationBean<FacesServlet> registration = new ServletRegistrationBean<>();
        registration.setServlet(new FacesServlet());
        registration.addUrlMappings("/faces/*", "*.jsf", "*.faces", "*.xhtml");
        registration.setLoadOnStartup(1);

        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("javax.faces.CONFIG_FILES", "/WEB-INF/faces-config-beans.xml,/WEB-INF/faces-config-nav.xml");
        registration.setInitParameters(initParameters);
        return registration;
    }

    @Bean
    public ServletContextInitializer servletContextInitializer() {
        return servletContext -> {
            servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
            servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", Boolean.TRUE.toString());
        };
    }

    @Bean
    public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
        return new ServletListenerRegistrationBean<ConfigureListener>(
                new ConfigureListener());
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
        // servletContext.setInitParameter("", "com.sun.faces.config.ConfigureListener");
        // servletContext.setInitParameter("", "");

    }

}
